<template>
  <div class="design-editor-container">
    <div class="editor-layout">
      <!-- Left sidebar with tools -->
      <div class="editor-sidebar">
        <new-designer-sidebar 
          :layers="canvasLayers"
          @add-shape="addShape"
          @add-element="addElement"
          @activate-tool="activateTool"
          @toggle-grid="toggleGrid"
          @toggle-ruler="toggleRuler"
          @color-change="setColor"
          @add-material="addMaterial"
          @add-text="addText"
          @apply-template="applyTemplate"
          @apply-text-style="applyTextStyle"
          @layer-updated="handleLayerUpdated"
          @layer-visibility="handleLayerVisibility"
          @layer-lock="handleLayerLock"
          @layer-selected="handleLayerSelected"
          @layer-deleted="handleLayerDeleted"
          @reorder-layers="handleReorderLayers"
          @add-commerce="addCommerceElement"
        />
      </div>
      
      <!-- Center canvas area -->
      <div class="editor-canvas-area">
        <div class="editor-toolbar">
          <el-button-group>
            <el-button size="small" icon="el-icon-copy-document" @click="copySelected">复制</el-button>
            <el-button size="small" icon="el-icon-delete" @click="deleteSelected">删除</el-button>
            <el-button size="small" icon="el-icon-top" @click="bringToFront">移到顶部</el-button>
            <el-button size="small" icon="el-icon-bottom" @click="sendToBack">移到底部</el-button>
          </el-button-group>
          
          <div class="canvas-actions">
            <el-button size="small" type="primary" @click="saveDesign">保存</el-button>
            <el-button size="small" @click="exportDesign">导出</el-button>
            <el-button size="small" @click="previewDesign">预览</el-button>
          </div>
        </div>
        
        <div class="canvas-container">
          <canvas ref="fabricCanvas" class="fabric-canvas"></canvas>
        </div>
      </div>
      
      <!-- Right properties and AI panel -->
      <div class="editor-properties">
        <el-tabs type="border-card">
          <el-tab-pane label="属性">
            <property-panel 
              v-if="selectedObject"
              :selected-object="selectedObject"
              @update-property="updateObjectProperty"
              @toggle-text-style="toggleTextStyle"
            />
            
            <div v-else class="no-selection-hint">
              <p>请选择一个对象来编辑属性</p>
            </div>
          </el-tab-pane>
          
          <el-tab-pane label="AI文生图">
            <ai-text2img-panel
              :params="aiText2ImgParams"
              :generated-images="generatedImages"
              @generate="generateAiImage"
              @add-to-canvas="addGeneratedImageToCanvas"
            />
          </el-tab-pane>
          
          <el-tab-pane label="AI图生图">
            <ai-img2img-panel
              :params="aiImg2ImgParams"
              :generated-images="generatedImg2ImgImages"
              @generate="generateImg2ImgImage"
              @add-to-canvas="addGeneratedImageToCanvas"
              @update-reference="handleReferenceImageUpload"
            />
          </el-tab-pane>
        </el-tabs>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, reactive, computed, onUnmounted, nextTick } from 'vue';
import * as fabric from "fabric";
import NewDesignerSidebar from '@/modules/designer/components/sidebar/NewDesignerSidebar.vue';
import PropertyPanel from '@/modules/designer/components/property/PropertyPanel.vue';
import AiText2imgPanel from '@/modules/designer/components/property/AiText2imgPanel.vue';
import AiImg2imgPanel from '@/modules/designer/components/property/AiImg2imgPanel.vue';
import { useLayerStore } from '@/modules/designer/store/layerStore';
import { useLayers } from '@/modules/designer/composables/useLayers';

// Canvas reference
const fabricCanvas = ref(null);
let canvas = null;

// Layer management
const layerStore = useLayerStore();
const { 
  canvasLayers, 
  addLayerFromObject, 
  updateLayer,
  removeLayer,
  selectLayer
} = useLayers(canvas);

// Editor state
const selectedColor = ref('#FF5722'); // Orange color like in the screenshot
const backgroundType = ref('color');
const backgroundColor = ref('#FFFFFF');
const selectedObject = ref(null);
const isTextObject = computed(() => {
  return selectedObject.value && selectedObject.value.type === 'text';
});

// AI文生图参数
const aiText2ImgParams = reactive({
  prompt: '',
  negative_prompt: '',
  model: 'sdxl',
  cfg_scale: 7,
  size: '768x768',
  sampler: 'DPM++ 2M Karras',
  seed: -1
});

// AI图生图参数
const aiImg2ImgParams = reactive({
  referenceImage: null,
  prompt: '',
  negative_prompt: '',
  denoising_strength: 0.7,
  cfg_scale: 7,
  size: '768x768',
  sampler: 'DPM++ 2M Karras',
  seed: -1
});

// 生成的图像结果
const generatedImages = reactive([]);
const generatedImg2ImgImages = reactive([]);

// Sample materials
const materials = reactive([
  { name: '花朵', url: '/materials/flower.svg' },
  { name: '星星', url: '/materials/star.svg' },
  { name: '图表', url: '/materials/chart.svg' },
]);

// Initialize the canvas
onMounted(async () => {
  await nextTick();
  canvas = new fabric.Canvas(fabricCanvas.value, {
    width: 600,
    height: 600,
    backgroundColor: backgroundColor.value
  });
  
  // Set up selection events
  canvas.on('selection:created', handleObjectSelected);
  canvas.on('selection:updated', handleObjectSelected);
  canvas.on('selection:cleared', handleSelectionCleared);
  
  // Set up object modification events
  canvas.on('object:modified', updateSelectedObjectProps);
  
  // Set up fabric canvas in the useLayers composable
  useLayers(canvas);
});

onUnmounted(() => {
  if (canvas) {
    canvas.dispose();
  }
});

// Handle selection events
function handleObjectSelected(e) {
  selectedObject.value = canvas.getActiveObject();
  updateSelectedObjectProps();
  
  // Update layer selection
  if (selectedObject.value && selectedObject.value.id) {
    selectLayer(selectedObject.value.id);
  }
}

function handleSelectionCleared() {
  selectedObject.value = null;
}

function updateSelectedObjectProps() {
  if (!selectedObject.value) return;
  
  // Update basic properties in the store
  const obj = selectedObject.value;
  updateLayer(obj.id, {
    left: Math.round(obj.left),
    top: Math.round(obj.top),
    width: Math.round(obj.width * obj.scaleX),
    height: Math.round(obj.height * obj.scaleY),
    angle: Math.round(obj.angle),
    visible: obj.visible !== false
  });
}

// Update object properties
function updateObjectProperty(property, value) {
  if (!selectedObject.value) return;
  
  const val = value !== undefined ? value : selectedObject.value[property];
  
  if (property === 'width') {
    selectedObject.value.set('scaleX', val / selectedObject.value.width);
  } else if (property === 'height') {
    selectedObject.value.set('scaleY', val / selectedObject.value.height);
  } else {
    selectedObject.value.set(property, val);
  }
  
  updateSelectedObjectProps();
  canvas.renderAll();
}

// Toggle text styles
function toggleTextStyle(property, value) {
  if (!selectedObject.value || !isTextObject.value) return;
  
  const currentValue = selectedObject.value[property];
  const newValue = currentValue === value ? (property === 'fontWeight' ? 'normal' : (property === 'fontStyle' ? 'normal' : false)) : value;
  
  selectedObject.value.set(property, newValue);
  canvas.renderAll();
  updateSelectedObjectProps();
}

// AI图像生成功能
function generateAiImage() {
  console.log('Generating AI image with params:', aiText2ImgParams);
  
  // 这里应该调用后端API进行实际生成
  // 模拟生成过程和结果
  setTimeout(() => {
    const newImage = {
      id: Date.now(),
      url: `/demo/ai-generated-${generatedImages.length + 1}.jpg`,
      prompt: aiText2ImgParams.prompt
    };
    generatedImages.push(newImage);
  }, 2000);
}

function generateImg2ImgImage() {
  if (!aiImg2ImgParams.referenceImage) return;
  
  console.log('Generating img2img with params:', aiImg2ImgParams);
  
  // 这里应该调用后端API进行实际生成
  // 模拟生成过程和结果
  setTimeout(() => {
    const newImage = {
      id: Date.now(),
      url: `/demo/img2img-generated-${generatedImg2ImgImages.length + 1}.jpg`,
      prompt: aiImg2ImgParams.prompt
    };
    generatedImg2ImgImages.push(newImage);
  }, 2000);
}

function handleReferenceImageUpload(file) {
  const reader = new FileReader();
  reader.onload = function(event) {
    aiImg2ImgParams.referenceImage = event.target.result;
  };
  reader.readAsDataURL(file.raw);
}

function addGeneratedImageToCanvas(image) {
  const imgObj = new Image();
  imgObj.src = image.url;
  imgObj.onload = function() {
    const fabricImage = new fabric.Image(imgObj);
    
    // Scale image to fit within canvas
    const maxSize = 300;
    if (fabricImage.width > maxSize || fabricImage.height > maxSize) {
      if (fabricImage.width > fabricImage.height) {
        fabricImage.scaleToWidth(maxSize);
      } else {
        fabricImage.scaleToHeight(maxSize);
      }
    }
    
    // Set unique ID
    fabricImage.id = Date.now().toString();
    
    canvas.add(fabricImage);
    canvas.setActiveObject(fabricImage);
    canvas.renderAll();
    
    // Add to layer system
    addLayerFromObject(fabricImage, "图像");
  };
}

// Tool functions
function addElement(type) {
  if (type === 'text') {
    addText();
  } else if (type === 'brush') {
    activateTool('brush');
  } else {
    addShape(type);
  }
}

function addText() {
  const text = new fabric.IText('输入文字', {
    left: 100,
    top: 100,
    fontFamily: 'Arial',
    fontSize: 24,
    fill: selectedColor.value
  });
  
  // Set unique ID
  text.id = Date.now().toString();
  text.name = "文字";
  
  canvas.add(text);
  canvas.setActiveObject(text);
  
  // Add to layer system
  addLayerFromObject(text, "文字");
}

function addShape(type) {
  let shape;
  const commonProps = {
    left: 100,
    top: 100,
    fill: selectedColor.value,
    stroke: '#000000',
    strokeWidth: 1
  };
  
  switch(type) {
    case 'rectangle':
      shape = new fabric.Rect({
        ...commonProps,
        width: 100,
        height: 100
      });
      shape.name = "矩形";
      break;
    case 'circle':
      shape = new fabric.Circle({
        ...commonProps,
        radius: 50
      });
      shape.name = "圆形";
      break;
    case 'triangle':
      shape = new fabric.Triangle({
        ...commonProps,
        width: 100,
        height: 100
      });
      shape.name = "三角形";
      break;
    case 'polygon':
      shape = new fabric.Polygon([
        { x: 50, y: 0 },
        { x: 100, y: 25 },
        { x: 100, y: 75 },
        { x: 50, y: 100 },
        { x: 0, y: 75 },
        { x: 0, y: 25 }
      ], commonProps);
      shape.name = "多边形";
      break;
    case 'line':
      shape = new fabric.Line([50, 50, 200, 200], {
        stroke: selectedColor.value,
        strokeWidth: 2
      });
      shape.name = "直线";
      break;
    default:
      return;
  }
  
  // Set unique ID
  shape.id = Date.now().toString();
  
  canvas.add(shape);
  canvas.setActiveObject(shape);
  
  // Add to layer system
  addLayerFromObject(shape, shape.name);
}

function activateTool(tool) {
  if (tool === 'brush') {
    canvas.isDrawingMode = !canvas.isDrawingMode;
    if (canvas.isDrawingMode) {
      canvas.freeDrawingBrush.color = selectedColor.value;
      canvas.freeDrawingBrush.width = 5;
    }
  }
}

function setColor(color) {
  selectedColor.value = color;
  
  if (canvas.isDrawingMode) {
    canvas.freeDrawingBrush.color = color;
  }
  
  if (selectedObject.value) {
    selectedObject.value.set('fill', color);
    canvas.renderAll();
    updateSelectedObjectProps();
  }
}

function addMaterial(material) {
  fabric.loadSVGFromURL(material.url, function(objects, options) {
    const loadedObject = fabric.util.groupSVGElements(objects, options);
    loadedObject.set({
      left: 100,
      top: 100,
      scaleX: 0.5,
      scaleY: 0.5
    });
    
    // Set unique ID
    loadedObject.id = Date.now().toString();
    loadedObject.name = material.name;
    
    canvas.add(loadedObject);
    canvas.setActiveObject(loadedObject);
    
    // Add to layer system
    addLayerFromObject(loadedObject, material.name);
  });
}

// 添加电商元素
function addCommerceElement(element) {
  console.log('Adding commerce element:', element);
  // 这里实现电商元素的添加逻辑
}

function applyTemplate(template) {
  // In a real implementation, this would load a predefined design
  console.log(`Applying template: ${template.name}`);
}

function applyTextStyle(style) {
  if (!selectedObject.value || !isTextObject.value) return;
  
  selectedObject.value.set({
    fontFamily: style.fontFamily,
    fontSize: style.fontSize,
    fontWeight: style.fontWeight,
    fontStyle: style.fontStyle,
    fill: style.color
  });
  
  canvas.renderAll();
  updateSelectedObjectProps();
}

// Background functions
function toggleGrid() {
  console.log('Toggle grid');
}

function toggleRuler() {
  console.log('Toggle ruler');
}

function changeBackground(type) {
  backgroundType.value = type;
  
  if (type === 'transparent') {
    canvas.backgroundColor = null;
  } else {
    canvas.backgroundColor = backgroundColor.value;
  }
  canvas.renderAll();
}

function setBackgroundColor(color) {
  backgroundColor.value = color;
  canvas.backgroundColor = color;
  canvas.renderAll();
}

// Object manipulation
function copySelected() {
  if (!selectedObject.value) return;
  
  selectedObject.value.clone(function(cloned) {
    cloned.set({
      left: cloned.left + 20,
      top: cloned.top + 20
    });
    
    // Set unique ID
    cloned.id = Date.now().toString();
    cloned.name = selectedObject.value.name ? selectedObject.value.name + " 副本" : "副本";
    
    canvas.add(cloned);
    canvas.setActiveObject(cloned);
    
    // Add to layer system
    addLayerFromObject(cloned, cloned.name);
  });
}

function deleteSelected() {
  if (!selectedObject.value) return;
  
  // Remove from layer system
  if (selectedObject.value.id) {
    removeLayer(selectedObject.value.id);
  }
  
  canvas.remove(selectedObject.value);
  selectedObject.value = null;
}

function bringToFront() {
  if (!selectedObject.value) return;
  selectedObject.value.bringToFront();
  canvas.renderAll();
}

function sendToBack() {
  if (!selectedObject.value) return;
  selectedObject.value.sendToBack();
  canvas.renderAll();
}

// Layer handling
function handleLayerUpdated(layer) {
  // Find the object on canvas
  const objects = canvas.getObjects();
  const obj = objects.find(o => o.id === layer.id);
  
  if (obj) {
    // Update object properties
    obj.set({
      left: layer.left,
      top: layer.top,
      scaleX: layer.width / obj.width,
      scaleY: layer.height / obj.height,
      angle: layer.angle
    });
    
    canvas.renderAll();
  }
}

function handleLayerVisibility(layer) {
  const objects = canvas.getObjects();
  const obj = objects.find(o => o.id === layer.id);
  
  if (obj) {
    obj.visible = layer.visible;
    canvas.renderAll();
  }
}

function handleLayerLock(layer) {
  const objects = canvas.getObjects();
  const obj = objects.find(o => o.id === layer.id);
  
  if (obj) {
    obj.selectable = !layer.locked;
    obj.evented = !layer.locked;
    
    if (layer.locked && selectedObject.value && selectedObject.value.id === layer.id) {
      canvas.discardActiveObject();
    }
    
    canvas.renderAll();
  }
}

function handleLayerSelected(layerId) {
  const objects = canvas.getObjects();
  const obj = objects.find(o => o.id === layerId);
  
  if (obj) {
    canvas.setActiveObject(obj);
    canvas.renderAll();
  }
}

function handleLayerDeleted(layerId) {
  const objects = canvas.getObjects();
  const obj = objects.find(o => o.id === layerId);
  
  if (obj) {
    canvas.remove(obj);
    canvas.renderAll();
  }
}

function handleReorderLayers(layers) {
  // Re-order canvas objects to match layer order
  const orderedIds = layers.map(l => l.id);
  const objects = canvas.getObjects();
  
  // Remove all objects
  canvas.clear();
  
  // Add them back in the new order
  orderedIds.forEach(id => {
    const obj = objects.find(o => o.id === id);
    if (obj) {
      canvas.add(obj);
    }
  });
  
  canvas.renderAll();
}

// Canvas actions
function saveDesign() {
  const json = canvas.toJSON(['id', 'name']);
  const jsonString = JSON.stringify(json);
  console.log('Design saved:', jsonString);
  
  // In a real application, you would save this to the backend
  alert('设计已保存');
}

function exportDesign() {
  const dataURL = canvas.toDataURL({
    format: 'png',
    quality: 1
  });
  
  const link = document.createElement('a');
  link.href = dataURL;
  link.download = 'design.png';
  link.click();
}

function previewDesign() {
  const dataURL = canvas.toDataURL();
  window.open(dataURL);
}
</script>

<style scoped>
.design-editor-container {
  height: calc(100vh - 64px); /* Adjust based on your header height */
  overflow: hidden;
}

.editor-layout {
  display: flex;
  height: 100%;
}

/* Left sidebar */
.editor-sidebar {
  width: 230px;
  background-color: #f5f5f5;
  border-right: 1px solid #e0e0e0;
  overflow: hidden;
  display: flex;
}

/* Center canvas area */
.editor-canvas-area {
  flex: 1;
  display: flex;
  flex-direction: column;
  background-color: #e9e9e9;
  overflow: hidden;
}

.editor-toolbar {
  height: 40px;
  padding: 0 15px;
  background-color: #fff;
  border-bottom: 1px solid #e0e0e0;
  display: flex;
  align-items: center;
  justify-content: space-between;
}

.canvas-container {
  flex: 1;
  position: relative;
  overflow: auto;
  display: flex;
  align-items: center;
  justify-content: center;
}

.fabric-canvas {
  background-color: #ffffff;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

/* Right properties panel */
.editor-properties {
  width: 280px;
  background-color: #f5f5f5;
  border-left: 1px solid #e0e0e0;
  padding: 0;
  overflow-y: auto;
}

.no-selection-hint {
  color: #999;
  text-align: center;
  padding: 20px 0;
}

@media (max-width: 1200px) {
  .editor-sidebar {
    width: 200px;
  }
  
  .editor-properties {
    width: 250px;
  }
}
</style>